﻿Imports Equipment.Core
Imports Equipment.DataAccess
Imports Equipment.Business
Imports Equipment.Model

Namespace Equipment
    <RequiresPageAcces(Page:=PageType.UserGroup)> _
    Public Class GroupController
        Inherits System.Web.Mvc.Controller


        Function Index() As ActionResult
            Dim tree = SiteDepartmentManager.GetTreeFor(Application.CurrentUserInfo)
            ViewData("SiteUserGroups") = tree
            ViewData("EntityType") = EntityType.Group
            If tree.Count() = 0 Then
                ViewData("SelectedSDepartmentID") = 0
            Else
                Dim firstSite = tree.First()
                If firstSite.Groups.Count > 0 Then
                    ViewData("SelectedDepartmentID") = firstSite.Groups(0).ID
                Else
                    ViewData("SelectedDepartmentID") = 0
                End If

            End If
            Return View()
        End Function

#Region "AJAX"
        <HttpPost()> _
        Function UpdateGroup(ByVal id As Integer, ByVal desc As String) As ActionResult

            Dim group As Group = group.GetByPrimaryKey(id)
            If group IsNot Nothing Then
                Dim oldDesc = group.Description
                group.Description = desc
                group.Save()
                ModificationHistory.Insert(EntityType.Group, desc, ModificationAction.Modified, Application.CurrentUserInfo.UserID, String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Description", oldDesc, desc), group.ID)
                NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.UserGroup_Modify, oldDesc, group)
            End If

            ViewData("SiteUserGroups") = SiteDepartmentManager.GetTreeFor(Application.CurrentUserInfo)
            Return PartialView("~/Views/Group/Controls/GroupTree.ascx", ViewData("SiteUserGroups"))
        End Function

        <HttpPost()> _
        Function CreateGroup(ByVal siteID As Integer, ByVal desc As String) As ActionResult

            Dim newGroup As Group = Group.Insert(siteID, desc)
            ModificationHistory.Insert(EntityType.Group, desc, Application.CurrentUserInfo.UserID, newGroup.ID)
            NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.UserGroup_Create, desc, newGroup)

            ViewData("SiteUserGroups") = SiteDepartmentManager.GetTreeFor(Application.CurrentUserInfo)
            Return PartialView("~/Views/Group/Controls/GroupTree.ascx", ViewData("SiteUserGroups"))
        End Function

        <HttpPost()> _
        Function GetGroupByDepartmentID(ByVal depID As Integer) As ActionResult

            ViewData("Groups") = GroupManager.GetAllByDepartmentFor(depID, Application.CurrentUserInfo)
            Return PartialView("~/Views/Group/Controls/FilteredGroupGrid.ascx", String.Empty)
        End Function
#End Region

    End Class
End Namespace